<template>
	<view class="page">
		<image class="login-bg" src="/static/login-B/pageBg.png" mode="aspectFill" style="width: 750rpx;"></image>
		<view class="title">
			<view>Hello！<br>欢迎来到国梦云仓</view>
		</view>

		<view class="form">
			<view class="tab">
				<view class="u-text-center u-flex-fill" style="color: black;">
					登录
				</view>
			</view>
			<view class="inputs_button">
				<view class="inputs">
					<view class="account">
						<input type="text" v-model="account" :adjust-position="false" placeholder="请输入账号" />
					</view>
					<view class="password">
						<input :type="pwdShow? 'text' : 'password'" v-model="password" :adjust-position="false"
							placeholder="请输入密码" />
						<u-icon :name="pwdShow ? 'eye' : 'eye-off'" color="#cccccc" size="24"
							@click="pwdShow=!pwdShow"></u-icon>
					</view>
				</view>
				
				<!-- 整合订阅授权的登录按钮 -->
				<view class="login-section">
					<button 
						class="login-btn"
						open-type="subscribeMessage"
						@click="handleLoginWithSubscribe"
						:subscribe-message-template-id-list="templateIdList"
						subscribe-message-scene="enterPage"
						:disabled="isLoggingIn"
					>
						{{ isLoggingIn ? '登录中...' : '登录并订阅消息' }}
					</button>
					
					<view class="auth-tip">
						登录即表示同意接收重要服务通知
					</view>
				</view>
				
				<!-- 授权状态提示 -->
				<view class="auth-status" v-if="authStatus">
					<text :class="['status-text', authStatus.type]">
						{{ authStatus.message }}
					</text>
				</view>
			</view>
		</view>
	</view>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { userApi } from '@/api/index.js'
import md5 from 'js-md5'
import { useSubscribeMessage } from '@/composables/useSubscribeMessage'

const userStore = useUserStore()

// 响应式数据
const account = ref("")
const password = ref("")
const vcode = ref("")
const loginType = ref(1)
const pwdShow = ref(false)
const pactChecked = ref(false)
const vcodeTime = ref(0)
const vcodeTimer = ref(null)
const isLoggingIn = ref(false) // 登录状态

// 使用订阅消息 Hook
const templateIdList = ['8BYCmgqMs93PA1OxJao3t5VxI-6XxBiR_jKuUVHqIWQ','Ujvb0IIzDKOrXOpn6x4GK8-95F7fDKTikONYnbUxaNc','C7_nn9FArkj5NSH1BSNPG0NBvznBh1rx1qZ8hwUPJOo'] //'ExFc4_BMBkSpEGNgLtaji2tXBjWwSpoPbkUki99hbgE',
	
const {
    hasSubscribed,
    isLoading: isSubscribing,
    authStatus,
    showReAuthTip,
    triggerSubscribe,
    checkSubscriptionStatus
} = useSubscribeMessage(templateIdList, {
    forceSubscribe: true, // 强制订阅
    autoCheckStatus: true // 自动检查状态
})

// 整合订阅授权的主登录方法
const handleLoginWithSubscribe = async () => {
    // 基础表单验证
    if (!validateForm()) {
        return
    }
    
    isLoggingIn.value = true
    authStatus.value = null
    
    try {
        // 第一步：进行订阅消息授权[1](@ref)
        const subscribeResult = await triggerSubscribe()
        if (subscribeResult) {
            // 授权成功，继续登录流程
            await performLogin()
        } else {
            // 授权失败，阻止登录
            authStatus.value = {
                type: 'error',
                message: '请授权订阅消息以继续使用'
            }
        }
    } catch (error) {
        console.error('登录流程错误:', error)
        authStatus.value = {
            type: 'error',
            message: '登录失败，请重试'
        }
    } finally {
        isLoggingIn.value = false
    }
}

// 表单验证（保持不变）
const validateForm = () => {
    if (!account.value.trim()) {
        uni.showToast({
            title: "请输入账号",
            icon: 'none'
        })
        return false
    }

    if (!password.value.trim()) {
        uni.showToast({
            title: "请输入密码",
            icon: 'none'
        })
        return false
    }
    
    return true
}

// 修改后的登录函数
const performLogin = async () => {
    try {
        // 获取微信登录code和用户信息（包含UnionID）
        const [wxCode, userInfo] = await Promise.all([
            getWxLoginCode(),
            getWxUserInfo() // 新增获取用户信息的函数
        ])
        console.log(wxCode, userInfo,'看看内容');
        // 调用登录接口，添加unionId参数
        const result = await userApi.login({
            username: account.value,
            password: md5(password.value),
            code: wxCode,
            unionId: userInfo.unionId // 新增unionId字段
        })

        // 保存token和用户信息
        if (result.data?.token) {
            uni.setStorageSync('token', result.data.token)
            uni.setStorageSync('userInfo', result.data.userdata[0])
            userStore.setUserInfo(result.data.userdata[0])
            
            uni.showToast({
                title: "登录成功",
                icon: 'success'
            })

            setTimeout(() => {
                uni.reLaunch({
                    url: `/pages/logistics/index`
                })
            }, 1500)
        } else {
            throw new Error('登录响应数据异常')
        }

    } catch (error) {
        console.error('登录失败:', error)
        throw error
    }
}

// 新增：获取用户信息（包含UnionID）
const getWxUserInfo = () => {
    return new Promise((resolve, reject) => {
        // 首先检查用户是否已授权
        wx.getSetting({ 
            success: (res) => {
                if (res.authSetting['scope.userInfo']) {
                    // 用户已授权，直接获取用户信息
                    wx.getUserInfo({
                        success: (userRes) => {
                            // 这里可以获取到包含unionId的用户信息
                            // 注意：unionId需要在解密后的数据中获取
                            resolve({
                                unionId: userRes.unionId,
                                userInfo: userRes.userInfo
                            })
                        },
                        fail: (err) => {
                            reject(new Error('获取用户信息失败: ' + err.errMsg))
                        }
                    })
                } else {
                    // 用户未授权，需要引导用户授权
                    reject(new Error('用户未授权获取用户信息'))
                }
            },
            fail: (err) => {
                reject(new Error('检查用户授权设置失败'))
            }
        })
    })
}
// 获取微信登录code（保持不变）
const getWxLoginCode = () => {
    return new Promise((resolve, reject) => {
        wx.login({
            success: (res) => {
                if (res.code) {
                    resolve(res.code)
                } else {
                    reject(new Error('获取微信登录凭证失败: ' + res.errMsg))
                }
            },
            fail: (err) => {
                reject(new Error('微信登录接口调用失败'))
            }, 
            timeout: 10000
        })
    })
}

// 生命周期
onMounted(() => {
    console.log('Login page mounted')
})

onUnmounted(() => {
    if (vcodeTimer.value) {
        clearInterval(vcodeTimer.value)
        vcodeTimer.value = null
    }
})
</script>
<style lang="scss" scoped>
	.page {
		min-height: 100vh;
		// background: url("../../static/login-B/pageBg.png") no-repeat top center;
		background-size: 100%;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		position: relative;
		.login-bg {
		  position: absolute;
		  left:0;
			right:0;
		  z-index: -10 !important;
		}

		.title {
			padding-top: 120rpx;
			padding-bottom: 70rpx;

			view {
				padding-left: 64rpx;
				font-size: 48rpx;
				font-weight: 700;
				color: #383838;
			}
		}

		.form {
			flex: 1;
			margin: 0 32rpx;
			border-radius: 40rpx;
			background-color: #fff;
			overflow: hidden;

			.tab {
				display: flex;
				align-items: center;
				justify-content: space-between;
				background-color: #ecf1fb;
				height: 100rpx;
				background: linear-gradient(180deg, #e3ebf9 0%, #ffffff 100%);

				view {
					width: 340rpx;
					line-height: 100rpx;
					text-align: center;
					color: #9e9e9e;
					position: relative;
				}

				view::after {
					content: '';
					width: 50rpx;
					height: 8rpx;
					display: block;
					background-color: #3264ed;
					border-radius: 4rpx;
					position: absolute;
					left: 50%;
					bottom: 14rpx;
					transform: translateX(-50%);
					opacity: 0;
				}

				view.select {
					background-color: #fff;
					color: #3264ed;
				}

				view.type1.select {
					border-radius: 0 40rpx 0 0;
				}

				view.type2.select {
					border-radius: 40rpx 0 0;
				}

				view.select::after {
					opacity: 1;
				}
			}

			.inputs_button {
				background-color: #fff;

				.inputs {
					padding: 150rpx 32rpx 0;
					margin-bottom: 80rpx;

					.account,
					.password,
					.vcode {
						height: 96rpx;
						border-radius: 20rpx;
						padding: 0 48rpx;
						display: flex;
						align-items: center;
						background-color: #f7fafc;

						input {
							flex: 1;
						}
					}

					.account {
						margin-bottom: 48rpx;
					}

					.vcode {
						text {
							text-wrap: nowrap;
							font-size: 26rpx;
							background-color: #fff;
							padding: 14rpx 30rpx;
							border-radius: 12rpx;
						}
					}
				}

				.button {
					padding: 0 32rpx;

					view {
						line-height: 96rpx;
						border-radius: 20rpx;
						text-align: center;
						font-size: 32rpx;
						background-color: #3264ed;
						color: #fff;
					}
				}
			}

		}

		.pact {
			display: flex;
			align-items: center;
			justify-content: center;
			padding-bottom: 120rpx;
			font-size: 24rpx;

			text {
				color: #3264ed;
			}

			radio {
				:deep(.uni-radio-input) {
					border: 1rpx solid #3264ed;
				}

				transform:scale(0.6)
			}
		}
	
		.login-section {
		        margin: 0 32rpx 48rpx;
		        text-align: center;
		        
		        .login-btn {
		            width: 100%;
		            height: 96rpx;
		            line-height: 96rpx;
		            background: #3264ed;
		            color: #fff;
		            border-radius: 20rpx;
		            font-size: 32rpx;
		            border: none;
		            
		            &:after {
		                border: none;
		            }
		            
		            &[disabled] {
		                background: #cccccc;
		                color: #666666;
		            }
		        }
		        
		        .auth-tip {
		            margin-top: 20rpx;
		            font-size: 24rpx;
		            color: #666;
		            text-align: center;
		        }
		    }
		    
		    .auth-status {
		        margin: 20rpx 32rpx 0;
		        padding: 20rpx;
		        border-radius: 12rpx;
		        text-align: center;
		        
		        .status-text {
		            font-size: 26rpx;
		            
		            &.success {
		                color: #07C160;
		                background: #f0f9f4;
		            }
		            
		            &.error {
		                color: #e64340;
		                background: #fef0f0;
		            }
		            
		            &.warning {
		                color: #f90;
		                background: #fff9e6;
		            }
		        }
		    }
	}
	/* 修改您style标签最后的样式规则 */
	::v-deep radio .wx-radio-input {
	  border-color: #3264ed !important;
	}
	
	::v-deep radio .wx-radio-input.wx-radio-input-checked {
	  border-color: #3264ed !important;
	  background-color: #3264ed !important;
	}
	
	::v-deep radio .wx-radio-input.wx-radio-input-checked::before {
	  color: transparent !important;
	  content: "" !important;
	}
	/* 更精确的选择器路径 */
	uni-radio .uni-radio-input {
	  border-color: #3264ed !important;
	}
	
	uni-radio .uni-radio-input.uni-radio-input-checked {
	  border-color: #3264ed !important;
	  background-color: #3264ed !important;
	}
</style>